package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author: yp
 * @Description:
 * @creat:2022/10/28/16:58
 */
@Component
public class RedisWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 从2022年 1月1号0时0分0秒开始的时间
     */
    private static final Long BEGIN_TIMESTAMP = 1640995200L ;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32 ;




    public Long nextId(String prefixKey){
//        生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

//        生成序列号
//        获取当前的日期，精确到天数
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + prefixKey + ":" + date);
//        拼接并返回
        return timestamp << COUNT_BITS | count;
    }


}
